package com.fingard.dsp.bank.directbank.bocom01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.springframework.stereotype.Component;

@Component("BOCOM01Transaction")
public class BOCOM01Transaction extends BOCOM01Base implements ITransaction {

    /**
     * 历史明细查询
     * @param p_req7516
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        return d_GetTrans(p_req7516, true, true);
    }

    public RetAtsTrans d_GetTrans(Req7516HisTrans p_req7516, boolean p_isHistory, boolean p_needWriteEnd) throws Exception {
        // 历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        retAts.writeStart();// 写返回ATS的统一头部信息
        tr_code = p_isHistory ? "310304" : "310303";
        String data_end = "1";
        String offset = "0";
        while (!"0".equals(data_end)) {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("body");
            if (p_isHistory) {
                xmlWriter.writeElementString("start_date", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlWriter.writeElementString("end_date", Format.Date8Format.format(tmpCalendarTo.getTime()));
            }

            if(StringHelper.hasAnyChar(p_req7516.higherLevelAct)){
                xmlWriter.writeElementString("acno", p_req7516.higherLevelAct);
            }else {
                xmlWriter.writeElementString("acno", p_req7516.actNum);
            }

            xmlWriter.writeElementString("offset", offset);
            if (p_isHistory) {
                Calendar yesterday = Calendar.getInstance();
                yesterday.setTime(new Date());
                yesterday.add(Calendar.DAY_OF_MONTH, -1);
                if (Format.Date8Format.format(tmpCalendarTo.getTime()).equals(Format.Date8Format.format(yesterday.getTime()))) {
                    if (Format.Date8Format.format(tmpCalendarFrom.getTime()).equals(Format.Date8Format.format(tmpCalendarTo.getTime()))) {
                        xmlWriter.writeElementString("yesterday_flag", "0");
                    } else {
                        return d_GetTransContainsYesterDay(p_req7516);
                    }
                } else {
                    xmlWriter.writeElementString("yesterday_flag", "1");
                }
            }
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            //String[] tmpStrRet=new String[]{"",FileHelper.readFileText("D:\\xmlRspTest\\rsp.txt","utf-8")};

            XmlTextReader tmpBkReader;
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmprspmsg = tmpBkReader.getFirstText("/ap/head/particular_info");

                    if (isActiveRetCode(tmpRetCode)) {
                        offset = tmpBkReader.getFirstText("/ap/body/offset");
                        String jj = tmpBkReader.getFirstText("/ap/body/data_end");
                        if ("".equals(jj)) {
                            data_end = "0";
                        } else {
                            data_end = tmpBkReader.getFirstText("/ap/body/data_end");
                        }
                        String serial_record = tmpBkReader.getFirstText("/ap/body/serial_record");
                        int FieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/field_num"));
                        int RecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/record_num"));
                        java.util.List<String[]> listStrings = DealMFSText(serial_record, '|', FieldNum, RecordNum);
                        if (listStrings.size() > 0) {
                            listStrings.remove(0);
                            for (String[] strings : listStrings) {
                                //备注
                                String frmcod=strings[23];
                                //上级账号不为空，发起二级账户流水查询，只需返回用途字段规则不为“代理”+对应二级账户号的流水
                                if(StringHelper.hasAnyChar(p_req7516.higherLevelAct)){
                                    if(frmcod.contains("代理"+p_req7516.actNum)){
                                        continue;
                                    }
                                }
//                                else {//上级账号为空，发起一级账户流水查询，只需返回用途字段规则不为“代理”的流水
//                                    if(frmcod.contains("代理")){
//                                        continue;
//                                    }
//                                }
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                // 状态|交易日期|交易时间|业务类型|流水号|流水序号|账号|户名|收支标志|币种|交易金额|余额|可用余额|对方账号|对方户名|对方地址|对方开户行行号|对方开户行行名|票据种类|票据号码|票据名称|票据签发日期|附言|备注|
                                // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
                                // 18 19 20 31 22 23
                                tmpRetDetail.actNum = strings[6];
                                tmpRetDetail.recAccBank = strings[17];
                                tmpRetDetail.recAccName = strings[14];
                                tmpRetDetail.recAccNum = strings[13];
                                tmpRetDetail.tranAmt = strings[10];
                                tmpRetDetail.receiptNo = strings[4];
                                if (strings[1].length() == 8) {
                                    StringBuilder stringBuilder = new StringBuilder(strings[1]);
                                    tmpRetDetail.tranDate = stringBuilder.insert(4, "-").insert(7, "-").toString();
                                } else {
                                    tmpRetDetail.tranDate = strings[1];
                                }
                                if (strings[2].length() == 6) {
                                    StringBuilder stringBuilder = new StringBuilder(strings[2]);
                                    tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + stringBuilder.insert(2, ":").insert(5, ":").toString();

                                } else {
                                    tmpRetDetail.tranTime = strings[2];
                                }
                                //tmpRetDetail.tranTime = strings[2];
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                // "借（支出）1，贷（收入）2"
                                if ("D".equals(strings[8]) || "8".endsWith(strings[9])) {
                                    if (tmpRetDetail.tranAmt.contains("-")) {
                                        tmpRetDetail.cdFlag = "2";
                                    } else {
                                        tmpRetDetail.cdFlag = "1";
                                    }
                                } else if ("C".equals(strings[8]) || "1".equals(strings[8])) {
                                    if (tmpRetDetail.tranAmt.contains("-")) {
                                        tmpRetDetail.cdFlag = "1";
                                    } else {
                                        tmpRetDetail.cdFlag = "2";
                                    }
                                } else {
                                    tmpRetDetail.cdFlag = strings[8];
                                }
                                tmpRetDetail.accBal = strings[11];

                                tmpRetDetail.abstr = pickupAbstr(strings[23], strings[22]);

                                tmpRetDetail.usage = strings[23];
                                tmpRetDetail.billType = "";
                                tmpRetDetail.billNum = "";
                                tmpRetDetail.payCode = "";
                                tmpRetDetail.urid = strings[1]+strings[4]+strings[5];
                                tmpRetDetail.receiptNo = strings[4];
                                tmpRetDetail.bnkSeqNo = strings[4];
                                nodeAnalysic(strings, tmpRetDetail, getCharset());
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {

                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmprspmsg);
                            break;
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmprspmsg);
                        break;

                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                    break;
                }

            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpStrRet[1]);
                break;
            }
        }

        if (!retAts.hasWrittenRespCode && retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }

        if (p_needWriteEnd) {
            retAts.writeEnd();
        }
        return retAts;
    }

    public RetAtsTrans d_GetTransContainsYesterDay(Req7516HisTrans p_req7516) throws Exception {
        String dateFrom = p_req7516.dateFrom;
        String dateTo = p_req7516.dateTo;
        p_req7516.dateFrom = dateTo;
        RetAtsTrans tmpTrans = d_GetTrans(p_req7516, true, true);
        if (tmpTrans.getRetAtsString().contains("<RespCode>0</RespCode>")) {
            Calendar yesterday = Calendar.getInstance();
            yesterday.setTime(new Date());
            yesterday.add(Calendar.DAY_OF_MONTH, -2);
            p_req7516.dateFrom = dateFrom;
            p_req7516.dateTo = Format.Date8Format.format(yesterday.getTime());
            RetAtsTrans tmpTrans1 = d_GetTrans(p_req7516, true, false);
            if (tmpTrans1.getRetAtsString().contains("<RespCode>0</RespCode>")) {
                XmlTextReader tmpBkReader;
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpTrans.getRetAtsString(), tmpSbMsg);
                if (tmpBkReader != null) {
                    while (tmpBkReader.read(tmpTrans.PATH_Detail)) {
                        tmpTrans1.writeXElement(tmpBkReader.readedXElement);
                    }
                }
                tmpTrans1.writeEnd();
                return tmpTrans1;
            } else {
                return tmpTrans1;
            }
        } else {
            return tmpTrans;
        }

    }

    /**
     * 当日明细查询调用历史明细查询方法
     * @param p_req7515
     * @return
     * @throws Exception
     */
    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        // 通用b2e0035
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        tmpReq7516.higherLevelAct=p_req7515.higherLevelAct;
        return d_GetTrans(tmpReq7516, false, true);
    }
}
